<script setup lang="ts">
import { uploadPublicFileApi } from '@/api/system/file/file'

interface OnCloseResolveType extends CloseResolveType {}
let onCloseResolve = function (_value: OnCloseResolveType) { }

const dialogRef = $ref<DialogInstance>()
const cropperRef = $ref<SyCropperInstance>()

let imgUrl = $ref('')
// 裁剪图片预览
let realTimePreviewStyle = $ref('')
let realTimePreviewImg = $ref('')
let loading = $ref(false)

async function showDialog(args: {
  imgUrl: string
}) {
  const dialogRes = dialogRef!.openDialog<OnCloseResolveType>({
    title: '裁剪图片',
  })

  imgUrl = args.imgUrl

  onCloseResolve = dialogRes.onCloseResolve

  return await dialogRes.dialogPrm
}

function realTime({ previewStyle, img }: {
  width: number
  height: number
  previewStyle: string
  img: string
}) {
  realTimePreviewStyle = previewStyle
  realTimePreviewImg = img
}

// 确定
async function confirm() {
  if (!cropperRef)
    return
  const { fileName, file } = await cropperRef.cropperSubmit()
  if (!file) {
    return
  }

  loading = true

  // 文件名称
  let name = fileName
  if (fileName.includes('http')) {
    const urlObj = new URL(fileName)
    const pathArray = urlObj.pathname.split('/')
    name = (pathArray.pop() || pathArray.pop()) ?? ''
  }
  const res = await uploadPublicFileApi(file, name).finally(() => {
    loading = false
  })

  // 更新用户信息
  await useUserStoreHook().updateLoginUserInfo({
    avatar: res.data.fileUrl,
  })

  Message({
    message: '上传成功',
    type: 'success',
  })
  onCloseResolve({
    type: true,
  })
}

defineExpose({ showDialog })
</script>

<template>
  <sy-dialog
    ref="dialogRef"
    hide-footer
    hide-full
  >
    <div un-flex="~ gap-10">
      <sy-cropper
        ref="cropperRef"
        :img="imgUrl"
        box-width="300"
        box-height="300"
        @real-time="realTime"
      />
      <div class="right">
        <div class="realTime-img">
          <img :style="realTimePreviewStyle" :src="realTimePreviewImg" alt="">
        </div>
        <el-button
          un-m-t="25px"
          type="primary"
          :loading="loading"
          @click="confirm"
        >
          提交
        </el-button>
      </div>
    </div>
  </sy-dialog>
</template>

<style scoped>
.right {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  .realTime-img {
    display: flex;
    border-radius: 50%;
    overflow: hidden;
    width: 200px;
    height: 200px;
  }
}
</style>
